package com.china.produce.system.util;

import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName
 * @Author niujie
 * @Version
 * @Description
 * @CreateTime 2022/5/1
 */
@Component
public class RedisUtil {

    @Autowired
    @Qualifier("redisTemplate2")
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 使用 SCAN 获取匹配的键
     *
     * @param pattern 键的匹配模式（如 "user:*"）
     * @return 匹配的键列表
     */
    public List<String> scanKeys(String pattern) {
        return redisTemplate.execute((RedisConnection connection) -> {
            List<String> keys = new ArrayList<>();
            ScanOptions options = ScanOptions.scanOptions()
                    .match(pattern) // 设置匹配模式
                    .count(100)     // 每次扫描的最大数量
                    .build();

            // 执行 SCAN
            try (Cursor<byte[]> cursor = connection.scan(options)) {
                while (cursor.hasNext()) {
                    keys.add(new String(cursor.next())); // 转换为字符串并添加到列表
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return keys;
        });
    }

    public boolean set(String key, Object value) {
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public boolean set(String key, Object value, long timeout, TimeUnit unit) {
        try {
            redisTemplate.opsForValue().set(key, value, timeout, unit);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    public String get(String key) {

        try {
            return (String) redisTemplate.opsForValue().get(key);
        }catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public Object eval(RedisScript<Integer> script, List<String> keys, Integer args){
        Object obj =  redisTemplate.execute(script, keys, args);
        return obj;
    }

}
